<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 客户货物信息
 *
 */
class Goods extends Backend
{
    /**
     * Goods模型对象
     * @var \app\admin\model\Goods
     */
    protected $model = null;
    
    protected $quickSearchField = ['GOODSID'];

    protected $defaultSortField = 'GOODSID,desc';

    protected $preExcludeFields = [''];
    protected $noNeedLogin      = ['*'];


    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\Goods;
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $wheres='';
        $crop=$this->request->get('CORP');
//        $crop='浙江壳牌';
        $field="*";
        if($crop){
            $wheres="CORP='$crop'";
            $field="CORP,GOODSID,GOODS,ename,CIQNO,GOODSKIND,unno,midu,tanktype,tankcbm,dbo.f_getallowtanktype(goodsid) as tank";
//            $field="*,dbo.f_getallowtanktype(goodsid) as tank";
        }
        $res = $this->model
            ->field($field)
            ->alias($alias)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->where($where)
            ->where($wheres)
            ->order($order)
//            ->fetchSql()->select();
            ->paginate($limit);
//        var_dump($res);die;
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $adminInfo          = $this->auth->getInfo();
            $data['GOODSID']='HW'. $this->microtime_format('YmdHisx',$this->microtime_float());
            $data['OP']=$adminInfo['nickname'];
            $data['OPTIME']=date('Y-m-d H:i:s',time());
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }

                $result = $this->model->save($data);
                //适装罐型
                $allow=[];
                foreach ($data['ALLOWTYPES'] as $item) {
                    $allow[]=['GOODSID'=>$this->model->GOODSID,'ALLOWTYPE'=>$item,'OP'=>$adminInfo['nickname'],'OPTIME'=>date('Y-m-d H:i:s',time())];
                }

                Db::table('x_goodstank')->insertAll($allow);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }
    /**
     * 编辑
     */
    public function edit()
    {
        $id  = $this->request->param('goodsid');
        if(!$id){
            $id  = $this->request->param($this->model->getPk());
        }

        $row = $this->model->field('*,dbo.f_get_goodscntrno(goodsid) as trno,dbo.f_getallowtanktype(goodsid) as ALLOWTYPES')->find($id);

        if(isset($row['ALLOWTYPES'])){
            $row['ALLOWTYPES']=explode('/', $row['ALLOWTYPES']);
        }

        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            $adminInfo          = $this->auth->getInfo();
            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                if(isset($data['ALLOWTYPES'])){
                    //删除原始罐型
                    Db::table('X_GOODSTANK')->where('GOODSID',$row['GOODSID'])->delete();
                    //适装罐型
                    $allow=[];
                    foreach ($data['ALLOWTYPES'] as $item) {
                        $allow[]=['GOODSID'=>$data['GOODSID'],'ALLOWTYPE'=>$item,'OP'=>$adminInfo['nickname'],'OPTIME'=>date('Y-m-d H:i:s',time())];
                    }
                    Db::table('x_goodstank')->insertAll($allow);
                }

                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        $this->success('', [
            'row' => $row,

        ]);
    }
}